package com.ywjt.platformbusiness.classify.fragment;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ywjt.platformbusiness.EventBusBean;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseVPFragment;
import com.ywjt.platformbusiness.classify.adapter.ShopHomeGoodsAdapter;
import com.ywjt.platformbusiness.constants.Constants;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.market.commongoods.activity.Activity_GoodsDetail;
import com.ywjt.platformbusiness.store.model.StoreGoodsListModel;
import com.ywjt.platformbusiness.util.JsonUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class ShopHomeGoodsFragment extends BaseVPFragment {
    private Context context;
    private SmartRefreshLayout refresh;
    private LinearLayout llNodata;
    private List<StoreGoodsListModel.ResultDTO.RecordsDTO> data;
    private RecyclerView rcGoods;
    private ShopHomeGoodsAdapter goodsAdapter;
    private PopupWindow popupWindow;
    private int type=0;//0 上架 1 下架
    private String typeId="";//品类id
    private Integer currentPage=1;
    private int count=0;

    private String updatePrice="";
    private String updateRate="";
    private String goodsId="";
    private String shopId="";//店铺id

    public static ShopHomeGoodsFragment newInstance(int type, String typeId,String shopId) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        arguments.putString("typeId",typeId);
        arguments.putString("shopId",shopId);
        ShopHomeGoodsFragment fl = new ShopHomeGoodsFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.goods_type_fragment,container,false);
        initView(view);
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Subscribe()
    public void change(EventBusBean eventBus){
        switch (eventBus.getCode()){
            case 20:
                typeId=eventBus.getMsg();
                getData();
                break;
        }
    }


    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (!isVisible){
            if (EventBus.getDefault().isRegistered(context)){
                EventBus.getDefault().unregister(context);
            }
        }

    }

    public void initView(View view){
        EventBus.getDefault().register(this);
        type=getArguments().getInt("type",0);
        typeId=getArguments().getString("typeId");
        shopId=getArguments().getString("shopId");
        context=getActivity();
        llNodata=view.findViewById(R.id.llNodata);
        refresh=view.findViewById(R.id.refresh);
        rcGoods=view.findViewById(R.id.rcCommon);
       setView();
    }

    /**
     * 在fragment首次可见时回调，可用于加载数据，防止每次进入都重复加载数据
     */
    @Override
    protected void onFragmentFirstVisible() {

    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("classId",typeId);
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize", String.valueOf(Constants.PAGESIZE));
            //map.put("lngStr","113.784208,34.758762");
            //map.put("status",String.valueOf(type));
            map.put("shopId",shopId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.getCommdityListByClassId, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), StoreGoodsListModel.class);
                        if (obj instanceof StoreGoodsListModel) {
                            StoreGoodsListModel model=(StoreGoodsListModel)obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcGoods.setVisibility(View.VISIBLE);
                                    data=model.getResult().getRecords();
                                    goodsAdapter=new ShopHomeGoodsAdapter(data);
                                    rcGoods.setLayoutManager(new GridLayoutManager(context,2,RecyclerView.VERTICAL,false));
                                    rcGoods.setAdapter(goodsAdapter);
                                    if (goodsAdapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            Activity_GoodsDetail.actionStart(context,model.getResult().getRecords().get(position).getId(),shopId);
                                        }
                                    }) ;
//                                    goodsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//                                        @Override
//                                        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                                            goodsId=data.get(position).getId();
//                                            if (type==0){
//                                                switch (view.getId()){
//                                                    case R.id.ivMore:
//                                                        //更多 弹出来弹窗
//                                                        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.popu_down_goods,null);
//                                                        LinearLayout llDownGoods=inflate.findViewById(R.id.llDownGoods);
//                                                        LinearLayout llEditPrice=inflate.findViewById(R.id.llEditPrice);
//                                                        llDownGoods.setOnClickListener(new View.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(View v) {
//                                                                WarningDialog dialog=new WarningDialog(context,"确认下架商品吗？","取消","确认","提示");
//                                                                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
//                                                                    @Override
//                                                                    public void doCancel() {
//                                                                        dialog.dismiss();
//                                                                    }
//
//                                                                    @Override
//                                                                    public void doConfirm() {
//                                                                        dialog.dismiss();
//                                                                        popupWindow.dismiss();
//                                                                        upOrDownGoods(data.get(position).getId());
//                                                                    }
//                                                                });
//                                                                dialog.show();
//                                                            }
//                                                        });
//
//                                                        llEditPrice.setOnClickListener(new View.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(View v) {
//                                                                //修改价格 弹出来弹窗
//                                                                CenterDialogPriceModify edit=new CenterDialogPriceModify(context,"修改价格",
//                                                                        data.get(position).getPrice()+"","20%");
//                                                                edit.setClicklistener(new CenterDialogPriceModify.ClickListenerInterface() {
//                                                                    @Override
//                                                                    public void confirm(String price,String rate) {
//                                                                        updatePrice=price;
//                                                                        updateRate=rate+"%";
//                                                                        edit.dismiss();
//                                                                        popupWindow.dismiss();
//                                                                        updatePrice(updatePrice);
//                                                                    }
//                                                                });
//                                                                edit.show();
//                                                            }
//                                                        });
//
//                                                        popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
//                                                                RelativeLayout.LayoutParams.WRAP_CONTENT);
//                                                        //设置背景,这个没什么效果，不添加会报错
//                                                        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//                                                        //设置点击弹窗外隐藏自身
//                                                        popupWindow.setFocusable(true);
//                                                        popupWindow.setOutsideTouchable(true);
//                                                        //相对于某一个控件的位置
//                                                        popupWindow.showAsDropDown(view,-240,-240);
//                                                        break;
//                                                }
//                                            }else {
//                                                switch (view.getId()){
//                                                    case R.id.ivMore:
//                                                        //更多 弹出来弹窗
//                                                        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.popu_up_goods,null);
//                                                        LinearLayout llUpGoods=inflate.findViewById(R.id.llUpGoods);
//                                                        LinearLayout llEditPrice=inflate.findViewById(R.id.llEditPrice);
//                                                        LinearLayout llDelete=inflate.findViewById(R.id.llDelete);
//                                                        llDelete.setOnClickListener(new View.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(View v) {
//                                                                WarningDialog dialog=new WarningDialog(context,"确认删除商品吗？","取消","确认","提示");
//                                                                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
//                                                                    @Override
//                                                                    public void doCancel() {
//                                                                        dialog.dismiss();
//                                                                    }
//
//                                                                    @Override
//                                                                    public void doConfirm() {
//                                                                        dialog.dismiss();
//                                                                        deleteGoods(data.get(position).getId());
//                                                                        popupWindow.dismiss();
//                                                                    }
//                                                                });
//                                                                dialog.show();
//                                                            }
//                                                        });
//                                                        llUpGoods.setOnClickListener(new View.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(View v) {
//                                                                WarningDialog dialog=new WarningDialog(context,"确认上架商品吗？","取消","确认","提示");
//                                                                dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
//                                                                    @Override
//                                                                    public void doCancel() {
//                                                                        dialog.dismiss();
//                                                                    }
//
//                                                                    @Override
//                                                                    public void doConfirm() {
//                                                                        dialog.dismiss();
//                                                                        upOrDownGoods(data.get(position).getId());
//                                                                        popupWindow.dismiss();
//                                                                    }
//                                                                });
//                                                                dialog.show();
//                                                            }
//                                                        });
//
//                                                        llEditPrice.setOnClickListener(new View.OnClickListener() {
//                                                            @Override
//                                                            public void onClick(View v) {
//                                                                //修改价格 弹出来弹窗
//                                                                CenterDialogPriceModify edit=new CenterDialogPriceModify(context,"修改价格",
//                                                                        data.get(position).getPrice()+"","20%");
//                                                                edit.setClicklistener(new CenterDialogPriceModify.ClickListenerInterface() {
//                                                                    @Override
//                                                                    public void confirm(String price,String rate) {
//                                                                        edit.dismiss();
//                                                                    }
//                                                                });
//                                                                edit.show();
//                                                            }
//                                                        });
//
//                                                        popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.WRAP_CONTENT,
//                                                                RelativeLayout.LayoutParams.WRAP_CONTENT);
//                                                        //设置背景,这个没什么效果，不添加会报错
//                                                        popupWindow.setBackgroundDrawable(new BitmapDrawable());
//                                                        //设置点击弹窗外隐藏自身
//                                                        popupWindow.setFocusable(true);
//                                                        popupWindow.setOutsideTouchable(true);
//                                                        //相对于某一个控件的位置
//                                                        popupWindow.showAsDropDown(view,-340,-240);
//                                                        break;
//                                                }
//                                            }
//                                        }
//                                    });
                                } else {
                                    rcGoods.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                goodsAdapter.notifyDataSetChanged();
                                if (goodsAdapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }


    public void setView(){
            data=new ArrayList<>();
            refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
            refresh.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(final RefreshLayout refreshLayout) {
                    refreshLayout.getLayout().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            currentPage = 1;
                            getData();
                        }
                    }, 1000);
                }
            });
            refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                    refreshLayout.getLayout().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            currentPage++;
                            getData();
                        }
                    }, 1000);
                }
            });
        }

}